class Store {
  constructor(options) {
    this.$options = options;
    this._mutations = options.mutations;
    this._actions = options.actions;
    this._getters = options.getters;
    // 对state进行响应式处理
    //   Vue.util.defineReactive()

    this._vm = new Vue({
      data() {
        return {
          $$state: options.state,
        };
      }
    });
    
    this.commit = this.commit.bind(this);
    this.dispatch = this.dispatch.bind(this);
  }
  get state() {
    return this._vm._data.$$state;
  }
  get getters() {
    let getterMap = {};
    Object.entries(this.$options.getters).forEach(([key, value]) => {
      getterMap[key] = value.call(this, this.state);
    });
    return getterMap
  }
  set state(val) {
    console.error("请使用replaceState重置state:", val);
  }
  commit(type, payload) {
    const entry = this._mutations[type];
    if (!entry) {
      console.error("unknown mutation！");
      return;
    }
    entry(this.state, payload);
  }
  dispatch(type, payload) {
    const entry = this._actions[type];
    if (!entry) {
      console.error("unknown actions！");
      return;
    }
    entry(this, payload);
  }
}
let Vue;
function install(_Vue) {
  Vue = _Vue;
  Vue.mixin({
    beforeCreate() {
      if (this.$options.store) {
        Vue.prototype.$store = this.$options.store;
      }
    },
  });
}
export default { Store, install };
